package com.bootdo.system.wechatUtil;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import lombok.extern.slf4j.Slf4j;
import sun.misc.BASE64Encoder;

import java.io.ByteArrayOutputStream;
import java.util.Hashtable;
@Slf4j
public class ZxingUtil {

    public static String enCode(String contents) {
        String base64Code = null;
        int width = 300, height = 300;
        Hashtable<Object, Object> hints = new Hashtable<Object, Object>();
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L);
        hints.put(EncodeHintType.MARGIN, 1);

        ByteArrayOutputStream bao = new ByteArrayOutputStream();
        try {
            BitMatrix byteMatrix = new MultiFormatWriter().encode(new String(contents.getBytes("UTF-8"),"iso-8859-1"), BarcodeFormat.QR_CODE, width, height);
            //删除白边
            byteMatrix = deleteWhite(byteMatrix);
            MatrixToImageWriter.writeToStream(byteMatrix, "png", bao);
        } catch (Exception e) {
            log.error("异常：", e);
        }
        base64Code =base64Code(bao.toByteArray());
        return base64Code;
    }

    /**
     * 删除白边
     * @param matrix
     * @return
     */
    private static BitMatrix deleteWhite(BitMatrix matrix) {
        int[] rec = matrix.getEnclosingRectangle();
        int resWidth = rec[2] + 1;
        int resHeight = rec[3] + 1;

        BitMatrix resMatrix = new BitMatrix(resWidth, resHeight);
        resMatrix.clear();
        for (int i = 0; i < resWidth; i++) {
            for (int j = 0; j < resHeight; j++) {
                if (matrix.get(i + rec[0], j + rec[1])){
                    resMatrix.set(i, j);
                }
            }
        }
        return resMatrix;
    }

    private static String  base64Code(byte[] b) {
        BASE64Encoder encoder = new BASE64Encoder();
        return encoder.encode(b);
    }
}
